<template>
  <div class="sidebar-with-operator-library">
    <!-- 算子库分类 -->
    <el-collapse v-model="activeCategory" :accordion="false">
      <el-collapse-item v-for="(category, index) in operatorCategories" :key="index" :title="category.name"
                        :name="index">
        <!-- 算子列表 -->
        <draggable
          :list="category.operators"
          :group="{ name: 'operator', pull: 'clone', put: false }"
          :clone="cloneOperator"
          @end="onDragEnd"
          ghost-class="ghost"
          drag-class="drag"
          class="operator-list"
        >
          <div v-for="operator in category.operators" :key="operator.id" class="operator-item">
            <span>{{ operator.name }}</span>
          </div>
        </draggable>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>
import {mapGetters} from 'vuex';
import draggable from 'vuedraggable';

export default {
  name: 'SidebarWithOperatorLibrary',
  components: {
    draggable
  },
  data() {
    return {
      activeCategory: 0 // 当前展开的分类索引
    };
  },
  computed: {
    ...mapGetters('operators', ['operatorCategories'])
  },
  methods: {
    cloneOperator(operator) {
      // 克隆算子以便在画布上使用
      return {...operator};
    },
    onDragEnd(event) {
      const clonedOperator = this.cloneOperator(event.item._underlying_vm_);
      this.$EventBus.$emit('operator-dragged', clonedOperator);
    }
  },
  mounted() {
    // 页面加载时触发获取算子库数据
    this.$store.dispatch('operators/fetchOperators');
  }
};
</script>

<style scoped>
.sidebar-with-operator-library {
  padding: 10px;
}

.operator-list {
  margin-top: 10px;
}

.operator-item {
  padding: 8px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin-bottom: 5px;
  background-color: #ffffff;
  cursor: grab;
}

.operator-item:hover {
  background-color: #f5f7fa;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.drag {
  opacity: 0.5;
}
</style>
